package com.yfp.operation.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson2.JSONObject;
import com.google.gson.JsonObject;
import com.yfp.common.core.utils.DateUtils;
import com.yfp.common.core.utils.StringUtils;
import com.yfp.common.datascope.annotation.DataScope;
import com.yfp.common.security.utils.SecurityUtils;
import com.yfp.operation.domain.*;
import com.yfp.operation.domain.dto.AssociationDTO;
import com.yfp.operation.domain.vo.AssociationVO;
import com.yfp.operation.mapper.MarAssociationMapper;
import com.yfp.operation.mapper.OrderListMapper;
import com.yfp.operation.service.*;
import com.yfp.operation.domain.*;
import com.yfp.operation.service.*;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.external.WxCpGroupJoinWayInfo;
import me.chanjar.weixin.cp.bean.external.WxCpGroupJoinWayResult;
import me.chanjar.weixin.cp.bean.external.WxCpUserExternalGroupChatInfo;
import me.chanjar.weixin.cp.bean.external.WxCpUserExternalGroupChatList;
import me.chanjar.weixin.cp.bean.external.contact.ExternalContact;
import me.chanjar.weixin.cp.bean.external.contact.WxCpExternalContactInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 社群
 * 
 * @CreateDate: 2024/7/5 14:30
 * @UpdateUser: 
 * @UpdateDate: 2024/7/5 14:30
 * @UpdateRemark: 暂无修改
 * @Version: 1.0
 */
@Service
@Slf4j
public class MarAssociationServiceImpl implements MarAssociationService {
    @Autowired
    private MarAssociationMapper associationMapper;
    @Autowired
    private WxCpService wxCpService;
    @Autowired
    private WxGroupChatService wxGroupChatService;
    @Autowired
    private WxGroupConfigService wxGroupConfigService;
    @Autowired
    private WxGroupMemberService wxGroupMemberService;
    @Autowired
    private PositionService positionService;
    @Resource
    private OrderListMapper orderListMapper;

    @Override
    public MarAssociation getById(Long id) {
        return associationMapper.getById(id);
    }

    @Override
    @DataScope(deptAlias = "a")
    public List<MarAssociation> findList(MarAssociation marAssociation) {
        return associationMapper.findList(marAssociation);
    }

    @Override
    @Transactional
    public void add(MarAssociation marAssociation) throws WxErrorException {
        PositionDO positionDO = positionService.getById(marAssociation.getPositionId());
        String qrCode = configGroupChat(positionDO.getPositonName(), marAssociation.getGroupChatId());
        marAssociation.setAsscoiationCode(qrCode);
        // 置空之前配置的企业微信群
        MarAssociation marAssociation1 = associationMapper.findByGroupChatId(marAssociation.getGroupChatId());
        if (null != marAssociation1) {
            associationMapper.editGroupChatIdNull(marAssociation1.getId());
        }

        Long deptId = SecurityUtils.getLoginUser().getSysUser().getDeptId();

        String username = SecurityUtils.getUsername();
        marAssociation.setCreateBy(username);
        marAssociation.setUpdateBy(username);
        marAssociation.setMember(0);
        marAssociation.setDeptId(deptId);
        associationMapper.add(marAssociation);
    }

    @Override
    public void edit(MarAssociation marAssociation) {
        associationMapper.edit(marAssociation);
    }

    @Override
    @Transactional
    public void syncGroupChat() throws WxErrorException {
        // 获取外部联系人的群组ID列表
        List<String> groupChatIds = new ArrayList<>();
        WxCpUserExternalGroupChatList wxCpUserExternalGroupChatList = wxCpService.getExternalContactService().listGroupChat(1000, null, 0, null);
        for (WxCpUserExternalGroupChatList.ChatStatus chatStatus : wxCpUserExternalGroupChatList.getGroupChatList()) {
            groupChatIds.add(chatStatus.getChatId());
//            log.info("wxCpUserExternalGroupChatList：{}", JSONObject.toJSONString(wxCpUserExternalGroupChatList));
            // 是否已存库
            try {
                WxGroupChat wxGroupChat = wxGroupChatService.getById(chatStatus.getChatId());
                WxCpUserExternalGroupChatInfo groupChatInfo = wxCpService.getExternalContactService().getGroupChat(chatStatus.getChatId(), 1);
                WxCpUserExternalGroupChatInfo.GroupChat groupChat = groupChatInfo.getGroupChat();
                if (null == wxGroupChat) {
                    wxGroupChat = new WxGroupChat();
                    wxGroupChat.setGroupChatId(groupChat.getChatId());
                    wxGroupChat.setGroupChatName(groupChat.getName());
                    wxGroupChat.setNotice(groupChat.getNotice());
                    wxGroupChat.setCreateTime(groupChat.getCreateTime());
                    wxGroupChat.setOwner(groupChat.getOwner());
                    wxGroupChat.setStatus(1);
                    wxGroupChat.setAdminList(JSONObject.toJSONString(groupChat.getAdminList()));
                    wxGroupChatService.add(wxGroupChat);
                } else {
                    wxGroupChat.setGroupChatId(groupChat.getChatId());
                    wxGroupChat.setGroupChatName(groupChat.getName());
                    wxGroupChat.setNotice(groupChat.getNotice());
                    wxGroupChat.setCreateTime(groupChat.getCreateTime());
                    wxGroupChat.setOwner(groupChat.getOwner());
                    wxGroupChat.setAdminList(JSONObject.toJSONString(groupChat.getAdminList()));
                    log.info("wxGroupChat：{}", JSONObject.toJSONString(wxGroupChat));
                    wxGroupChatService.edit(wxGroupChat);
                }

                wxGroupMemberService.updateStatus(groupChat.getChatId());
                // 同步群数据 扣的是之前自己收的没收到账的
                String cursor = null;
                for (WxCpUserExternalGroupChatInfo.GroupMember groupMember : groupChat.getMemberList()) {
//                log.info("同步群成员：userId: {}，chatId: {}", groupMember.getUserId(), groupChat.getChatId());
                    WxGroupMember wxGroupMember = wxGroupMemberService.getByIdAndGroupChatId(groupMember.getUserId(), groupChat.getChatId());
//                log.info("同步群成员：wxGroupMember： {}", wxGroupMember);
                    if (null == wxGroupMember) {
                        // 获取用户消息
                        wxGroupMember = new WxGroupMember();
//                        if (groupMember.getType() == 2) {
//                            WxCpExternalContactInfo externalContactInfo = null;
//                            try {
//                                externalContactInfo = wxCpService.getExternalContactService().getContactDetail(groupMember.getUserId(), cursor);
//                                cursor = externalContactInfo.getNextCursor();
//                                ExternalContact wxCpUser = externalContactInfo.getExternalContact();
//                                wxGroupMember.setGender(wxCpUser == null || wxCpUser.getGender() == null ? "0" : wxCpUser.getGender() + "");
//                                wxGroupMember.setAvatar(wxCpUser == null ? "" : wxCpUser.getAvatar());
//
//
//                            } catch (Exception e) {
//                                log.info(e.getMessage());
//                                wxGroupMember.setGender("0");
//                            }
//                        } else {
//
//                        }
                        wxGroupMember.setGender("0");
                        wxGroupMember.setStatus(1);
                        wxGroupMember.setUserId(groupMember.getUserId());
                        wxGroupMember.setGroupNickname(groupMember.getGroupNickname());
                        wxGroupMember.setName(groupMember.getName());
                        wxGroupMember.setType(groupMember.getType());
                        wxGroupMember.setJoinTime(groupMember.getJoinTime());
                        wxGroupMember.setUnionId(groupMember.getUnionId());
                        wxGroupMember.setJoinScene(groupMember.getJoinScene());
                        wxGroupMember.setGroupChatId(groupChat.getChatId());
                        wxGroupMemberService.add(wxGroupMember);
                    } else {
                        wxGroupMember.setGroupNickname(groupMember.getGroupNickname());
                        wxGroupMember.setName(groupMember.getName());
                        wxGroupMember.setType(groupMember.getType());
                        wxGroupMember.setJoinTime(groupMember.getJoinTime());
                        wxGroupMember.setUnionId(groupMember.getUnionId());
                        wxGroupMember.setJoinScene(groupMember.getJoinScene());
                        wxGroupMember.setStatus(1);
                        wxGroupMemberService.edit(wxGroupMember);
                    }
                }
                // 查看是否自动生成
                hostGroupChat(groupChatInfo);
//            log.info("用户人数：{}", groupChat.getMemberList().size());
                MarAssociation marAssociation = associationMapper.findByGroupChatId(groupChatInfo.getGroupChat().getChatId());
                if (null != marAssociation) {
                    marAssociation.setGroupChatName(groupChat.getName());
                    marAssociation.setMember(groupChat.getMemberList().size());
                    log.info("社群名称：{}，用户人数：{}", groupChat.getName(), groupChat.getMemberList().size());
                    associationMapper.edit(marAssociation);
                }
            } catch (Exception e) {
                log.error("同步群异常：{}", e);
            }
        }

        if (!groupChatIds.isEmpty()) {
            wxGroupChatService.editStatusNotInGroupChatIds(groupChatIds);
        }
    }

    @Override
    @Transactional
    public String configGroupChat(String positonName, String groupChatId) throws WxErrorException {
        // 获取外部联系人的群组ID列表
        WxGroupChat wxGroupChat1 = wxGroupChatService.getById(groupChatId);
        String groupName = wxGroupChat1.getGroupChatName().replaceAll("\\d", "");

        WxCpGroupJoinWayInfo.JoinWay joinWay = new WxCpGroupJoinWayInfo.JoinWay();
        joinWay.setRemark(positonName);
        joinWay.setScene(1);
        joinWay.setAutoCreateRoom(1);
        joinWay.setRoomBaseName(groupName);
        joinWay.setRoomBaseId(1);
        joinWay.setState(positonName);
        joinWay.setChatIdList(Arrays.asList(groupChatId));
        WxCpGroupJoinWayInfo wxCpGroupJoinWayInfo = new WxCpGroupJoinWayInfo();
        wxCpGroupJoinWayInfo.setJoinWay(joinWay);
        WxCpGroupJoinWayResult wxCpGroupJoinWayResult = wxCpService.getExternalContactService().addJoinWay(wxCpGroupJoinWayInfo);
//        log.info("wxCpUserExternalGroupChatList: {}", JSONObject.toJSONString(wxCpGroupJoinWayResult));

        WxGroupConfig wxGroupConfig = new WxGroupConfig();
        wxGroupConfig.setConfigId(wxCpGroupJoinWayResult.getConfigId());
        wxGroupConfig.setRemark(positonName);
        wxGroupConfig.setScene(1);
        wxGroupConfig.setState(positonName);
        wxGroupConfig.setChatIdList(JSONObject.toJSONString(Arrays.asList(groupChatId)));
        wxGroupConfig.setRoomBaseId(1);
        wxGroupConfig.setRoomBaseName("");
        wxGroupConfigService.add(wxGroupConfig);
        WxCpGroupJoinWayInfo joinWay1 = wxCpService.getExternalContactService().getJoinWay(wxCpGroupJoinWayResult.getConfigId());

        WxGroupChat wxGroupChat = wxGroupChatService.getById(groupChatId);
        wxGroupChat.setConfigId(wxGroupChat.getConfigId());
        wxGroupChat.setQrCode(joinWay1.getJoinWay().getQrCode());
        wxGroupChatService.edit(wxGroupChat);
        return wxGroupChat.getQrCode();
    }

    @Override
    public List<MarAssociation> findByPositionId(String positionId) {
        return associationMapper.findByPositionId(positionId);
    }

    @Override
    public MarAssociation findByGroupChatId(String groupChatId) {
        return associationMapper.findByGroupChatId(groupChatId);
    }

    public void hostGroupChat(WxCpUserExternalGroupChatInfo wxCpUserExternalGroupChatInfo) {
        String groupName = wxCpUserExternalGroupChatInfo.getGroupChat().getName().replaceAll("\\d", "");
        List<MarAssociation> marAssociations = associationMapper.findByGroupChatNameLike(groupName);
        if (!StringUtils.isEmpty(groupName) && !marAssociations.isEmpty()) {
            MarAssociation marAssociation = associationMapper.findByGroupChatId(wxCpUserExternalGroupChatInfo.getGroupChat().getChatId());
            if (null == marAssociation) {
                marAssociation = new MarAssociation();
                BeanUtils.copyProperties(marAssociations.get(0), marAssociation);
                marAssociation.setGroupChatId(wxCpUserExternalGroupChatInfo.getGroupChat().getChatId());
                marAssociation.setGroupChatName(wxCpUserExternalGroupChatInfo.getGroupChat().getName());
                associationMapper.add(marAssociation);
                WxGroupChat hostWxGroupChat = wxGroupChatService.getById(marAssociations.get(0).getGroupChatId());
                WxGroupChat wxGroupChat = wxGroupChatService.getById(wxCpUserExternalGroupChatInfo.getGroupChat().getChatId());
                wxGroupChat.setQrCode(hostWxGroupChat.getQrCode());
                wxGroupChatService.edit(wxGroupChat);
            }
        }
    }


    /**
     * 社群数据明细列表
     *
     * @param associationDTO
     * @return
     */
    @Override
    public List<AssociationVO> associationDataInfo(AssociationDTO associationDTO) {

        List<AssociationVO> list = associationMapper.associationDataInfo(associationDTO);

        return list;
    }

    /**
     * 社群数据明细列表补全
     *
     * @param list
     * @return
     */
    @Override
    public List<AssociationVO> complementDataInfo(List<AssociationVO> list, AssociationDTO associationDTO) {

        if (CollUtil.isEmpty(list)) {
            return list;
        }

        List<String> positionIds = list.stream().map(item -> item.getPositionId()).toList();
        // 下单用户数
        log.info("下单用户数 startTime:{}", DateUtils.getTime());
        associationDTO.setPositionIds(positionIds);
        List<AssociationVO> purchaseClientNumList = associationMapper.purchaseClientNum(associationDTO);
        log.info("下单用户数 startTime:{}, purchaseClientNumList:{}", DateUtils.getTime(), JSONObject.toJSONString(purchaseClientNumList));
        Map<String, AssociationVO> purchaseClientNumMap = purchaseClientNumList.stream().collect(Collectors.toMap(AssociationVO::getPositionId, s->s));

        // 复购人数
        log.info("复购人数 startTime:{}", DateUtils.getTime());
        List<AssociationVO> repeatedlyBuyNums = associationMapper.repeatedlyBuyNum(positionIds, associationDTO.getStartTime(), associationDTO.getEndTime(), 2);
        Map<String, AssociationVO> repeatedlyMap = repeatedlyBuyNums.stream().collect(Collectors.toMap(AssociationVO::getPositionId, s->s));
        // 退款
        log.info("退款 startTime:{}", DateUtils.getTime());
        List<AssociationVO> purchaseNumList = associationMapper.purchaseNum(positionIds, associationDTO.getStartTime(), associationDTO.getEndTime(), 1, null);
        Map<String, AssociationVO> purchaseNumMap = purchaseNumList.stream().collect(Collectors.toMap(AssociationVO::getPositionId, s->s));
        // 销售gvm
        log.info("销售gvm startTime:{}", DateUtils.getTime());
        List<AssociationVO> saleMoneyList = orderListMapper.saleMoney(positionIds, associationDTO.getStartTime(), associationDTO.getEndTime());
        Map<String, BigDecimal> saleMoneyMap = saleMoneyList.stream().collect(Collectors.toMap(AssociationVO::getPositionId, AssociationVO::getSaleMoney));
        // 成员数量
        log.info("成员数量 startTime:{}， param: {}", DateUtils.getTime(), associationDTO);
        List<AssociationVO> memberNumList = associationMapper.getPositionMemberNum(associationDTO);
        log.info("endTime:{}, memberNumList:{}", DateUtils.getTime(), JSONObject.toJSONString(memberNumList));
        Map<String, Integer> memberNumMap = memberNumList.stream().collect(Collectors.toMap(AssociationVO::getPositionId, AssociationVO::getMember));

        for (AssociationVO associationVO : list) {
            associationVO.setBuyClientNum(0);

            if (memberNumMap.containsKey(associationVO.getPositionId())) {
                associationVO.setMember(memberNumMap.get(associationVO.getPositionId()));
            }else {
                associationVO.setMember(0);
            }

            // 购买人数、新用户购买数
            log.info("CLIENTMAP:{}", JSONObject.toJSONString(purchaseClientNumMap.get(associationVO.getPositionId())));
            if (purchaseClientNumMap.containsKey(associationVO.getPositionId())) {
                AssociationVO associationVO1 = purchaseClientNumMap.get(associationVO.getPositionId());
                associationVO.setBuyNewClientNum(associationVO1.getBuyNewClientNum());
                associationVO.setBuyClientNum(associationVO1.getBuyClientNum());
            } else {
                associationVO.setBuyNewClientNum(0);
                associationVO.setBuyClientNum(0);
            }

            // 转化率
            BigDecimal conversionRate = BigDecimal.valueOf(0.00);
            if (associationVO.getMember() != 0) {
                conversionRate = BigDecimal.valueOf(associationVO.getBuyClientNum()).divide(BigDecimal.valueOf(associationVO.getMember()), 4, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100));
            }
            associationVO.setConversionRate(conversionRate);

            // 新用户下单占比
            BigDecimal newClientBuyProportion = BigDecimal.valueOf(0.00);
            if (associationVO.getMember() != 0) {
                newClientBuyProportion = BigDecimal.valueOf(associationVO.getBuyNewClientNum()).divide(BigDecimal.valueOf(associationVO.getMember()), 4, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100));
            }
            associationVO.setNewClientBuyProportion(newClientBuyProportion);

            // 复购人数
            if (repeatedlyMap.containsKey(associationVO.getPositionId())) {
                AssociationVO associationVO1 = repeatedlyMap.get(associationVO.getPositionId());
                associationVO.setRepeatedlyBuyNum(associationVO1.getRepeatedlyBuyNum());
                associationVO.setBuyNum(associationVO1.getBuyNum());
            } else {
                associationVO.setRepeatedlyBuyNum(0);
                associationVO.setBuyNum(0);
            }

            // 销售gmv
            if (saleMoneyMap.containsKey(associationVO.getPositionId())) {
                associationVO.setSaleMoney(saleMoneyMap.get(associationVO.getPositionId()));
            } else {
                associationVO.setSaleMoney(BigDecimal.valueOf(0));
            }


            // 复购率
            BigDecimal repeatedlyBuyRate = BigDecimal.valueOf(0.00);
            if (associationVO.getBuyNum() != 0) {
                repeatedlyBuyRate = BigDecimal.valueOf(associationVO.getRepeatedlyBuyNum()).divide(BigDecimal.valueOf(associationVO.getBuyNum()), 4, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100));
            }
            associationVO.setRepeatedlyBuyRate(repeatedlyBuyRate);

            // 用户下单数和退款数
            if (purchaseNumMap.containsKey(associationVO.getPositionId())) {
                AssociationVO associationVO1 = purchaseNumMap.get(associationVO.getPositionId());
                associationVO.setPurchaseNum(associationVO1.getPurchaseNum());
                associationVO.setRefundNum(associationVO1.getRefundNum());
            } else {
                associationVO.setPurchaseNum(0);
                associationVO.setRefundNum(0);
            }

            log.info("退款单数:{},下单数:{},点位id:{}",associationVO.getRefundNum(),associationVO.getPurchaseNum(),associationVO.getGroupChatId());

            // 退款率
            BigDecimal refundRate = BigDecimal.valueOf(0.00);
            if (associationVO.getPurchaseNum() != 0) {
                refundRate = BigDecimal.valueOf(associationVO.getRefundNum()).divide(BigDecimal.valueOf(associationVO.getPurchaseNum()), 4, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100));
            }
            associationVO.setRefundRate(refundRate);

            // 运营前三天下单用户数
            log.info("运营前三天下单用户数 startTime:{}", DateUtils.getTime());
            Integer clientNum = getStartTime(associationVO.getPositionId(), null);
            log.info("startTime:{}", DateUtils.getTime());
            //留存率
            BigDecimal keepRate = BigDecimal.valueOf(0.00);
            if (clientNum != 0) {
                keepRate = BigDecimal.valueOf(associationVO.getRepeatedlyBuyNum()).divide(BigDecimal.valueOf(clientNum), 4, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100));
            }
            associationVO.setKeepRate(keepRate);

            log.info("销售gmv:{},成员数量:{}",associationVO.getSaleMoney(),associationVO.getMember());
            // 客单价
            BigDecimal averagePrice = BigDecimal.valueOf(0.00);
            if (associationVO.getMember() != 0) {
                averagePrice = associationVO.getSaleMoney().divide(BigDecimal.valueOf(associationVO.getMember()), 2, RoundingMode.HALF_UP);
            }
            associationVO.setAveragePrice(averagePrice);
        }

        return list;
    }


    /**
     * 获取运营前三天用户数
     */
    public Integer getStartTime(String positionId, String groupChatId) {
        AssociationDTO associationDTO1 = positionService.startTime(positionId);
        if (BeanUtil.isEmpty(associationDTO1)) {
            return 0;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(associationDTO1.getStartTime());
        // 加2天
        calendar.add(Calendar.DAY_OF_YEAR, 2);
        // 设置为当天的最后一秒
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        Date endTime = calendar.getTime();
        associationDTO1.setEndTime(endTime);
        associationDTO1.setPositionId(positionId);
        associationDTO1.setGroupChatId(groupChatId);
        Integer clientNum = associationMapper.getClientNum(associationDTO1);
        return clientNum;
    }


    /**
     * 点位社群列表
     *
     * @param associationDTO
     * @return
     */
    @Override
    public List<AssociationVO> positionAssociation(AssociationDTO associationDTO) {
        List<AssociationVO> list = associationMapper.positionAssociation(associationDTO);
        return list;
    }

    /**
     * 补全点位社群列表
     *
     * @param list
     * @param associationDTO
     * @return
     */
    @Override
    public List<AssociationVO> complementPositionAssociation(List<AssociationVO> list, AssociationDTO associationDTO) {

        if (CollUtil.isEmpty(list)) {
            return list;
        }
        List<String> groupChatIds= list.stream().map(item -> item.getGroupChatId()).toList();
        // 下单数
        List<AssociationVO> associationVOS = orderListMapper.findClientNum(groupChatIds, associationDTO.getStartTime(), associationDTO.getEndTime());
        Map<String, AssociationVO> purchaseClientNumMap = associationVOS.stream().collect(Collectors.toMap(AssociationVO::getGroupChatId, s->s));

        // 下单客户数、复购数
        List<AssociationVO> associationVOS1 = orderListMapper.repeatedlyBuyNum(groupChatIds, associationDTO.getStartTime(), associationDTO.getEndTime(), 1);
        Map<String, AssociationVO> repeatedlyMap = associationVOS1.stream().collect(Collectors.toMap(AssociationVO::getGroupChatId, s->s));


        // 下单、退款单数
        List<AssociationVO> associationVOS2 = orderListMapper.purchaseNum(groupChatIds, 4, associationDTO.getStartTime(), associationDTO.getEndTime());
        Map<String, AssociationVO> purchaseNumMap = associationVOS2.stream().collect(Collectors.toMap(AssociationVO::getGroupChatId, s->s));


        List<AssociationVO> saleMoneyList = orderListMapper.saleGmv(groupChatIds, associationDTO.getStartTime(), associationDTO.getEndTime());
        Map<String, BigDecimal> saleMoneyMap = saleMoneyList.stream().collect(Collectors.toMap(AssociationVO::getGroupChatId, AssociationVO::getSaleMoney));

        log.info("成员数量 startTime:{}， param: {}", DateUtils.getTime(), associationDTO);
        List<AssociationVO> memberNumList = associationMapper.getGroupChatIdsMemberNum(groupChatIds, associationDTO.getEndTime());
        log.info("endTime:{}, memberNumList:{}", DateUtils.getTime(), JSONObject.toJSONString(memberNumList));
        Map<String, Integer> memberNumMap = memberNumList.stream().collect(Collectors.toMap(AssociationVO::getGroupChatId, AssociationVO::getMember));


        for (AssociationVO associationVO : list) {
            if (memberNumMap.containsKey(associationVO.getGroupChatId())) {
                associationVO.setMember(memberNumMap.get(associationVO.getGroupChatId()));
            }else {
                associationVO.setMember(0);
            }
            // 下单用户数、下单新用户数
            AssociationVO associationVO1 = purchaseClientNumMap.get(associationVO.getGroupChatId());
            if (associationVO1 != null) {
                associationVO.setBuyClientNum(associationVO1.getBuyClientNum());
                associationVO.setBuyNewClientNum(associationVO1.getBuyNewClientNum());
            } else {
                associationVO.setBuyClientNum(0);
                associationVO.setBuyNewClientNum(0);
            }

            // 转化率
            BigDecimal conversionRate = BigDecimal.valueOf(0.00);
            // 新用户下单占比
            BigDecimal newClientBuyProportion = BigDecimal.valueOf(0.00);

            if (associationVO.getMember() != 0) {
                conversionRate = BigDecimal.valueOf(associationVO.getBuyClientNum()).divide(BigDecimal.valueOf(associationVO.getMember()), 4, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100));
                newClientBuyProportion = BigDecimal.valueOf(associationVO.getBuyNewClientNum()).divide(BigDecimal.valueOf(associationVO.getMember()), 4, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100));
            }
            associationVO.setConversionRate(conversionRate);
            associationVO.setNewClientBuyProportion(newClientBuyProportion);

            // 下单客户数
            Integer buyNum = 0;
            // 复购数
            Integer repeatedlyBuyNum = 0;
            // 复购人数
            AssociationVO associationVO2 = repeatedlyMap.get(associationVO.getGroupChatId());
            if (null != associationVO2) {
                repeatedlyBuyNum = associationVO2.getRepeatedlyBuyNum();
                buyNum = associationVO2.getBuyNum();
            }

            // 复购率
            BigDecimal repeatedlyBuyRate = BigDecimal.valueOf(0.00);
            if (buyNum != 0) {
                repeatedlyBuyRate = BigDecimal.valueOf(repeatedlyBuyNum).divide(BigDecimal.valueOf(buyNum), 4, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100));
            }
            associationVO.setRepeatedlyBuyRate(repeatedlyBuyRate);

            // 退款单数
            Integer refundNum = 0;
            // 下单数
            Integer purchaseNum = 0;
            AssociationVO associationVO3 = purchaseNumMap.get(associationVO.getGroupChatId());
            if (null != associationVO3){
                refundNum = associationVO3.getRefundNum();
                purchaseNum = associationVO3.getPurchaseNum();
            }

            log.info("退款单数:{},下单数:{},群id:{}",refundNum,purchaseNum,associationVO.getGroupChatId());

            // 退款率
            BigDecimal refundRate = BigDecimal.valueOf(0.00);
            if (purchaseNum != 0) {
                refundRate = BigDecimal.valueOf(refundNum).divide(BigDecimal.valueOf(purchaseNum), 4, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100));
            }
            associationVO.setRefundRate(refundRate);

            // 运营前三天下单用户数
            Integer clientNum = getStartTime(associationVO.getPositionId(), associationVO.getGroupChatId());
            log.info("=================:clientNum: {} , repeatedlyBuyNum: {}",clientNum, repeatedlyBuyNum);
            //留存率
            BigDecimal keepRate = BigDecimal.valueOf(0.00);
            if (clientNum != 0) {
                keepRate = BigDecimal.valueOf(repeatedlyBuyNum).divide(BigDecimal.valueOf(clientNum), 4, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100));
            }
            associationVO.setKeepRate(keepRate);

            // 销售gvm
            BigDecimal saleGmv = BigDecimal.valueOf(0);
            BigDecimal bigDecimal = saleMoneyMap.get(associationVO.getGroupChatId());
            if (null != bigDecimal){
                saleGmv = bigDecimal;
            }

            log.info("销售gvm:{},成员数量:{}",saleGmv,associationVO.getMember());

            // 客单价
            BigDecimal averagePrice = BigDecimal.valueOf(0.00);
            if (associationVO.getMember() != 0) {
                averagePrice = saleGmv.divide(BigDecimal.valueOf(associationVO.getMember()), 2, RoundingMode.HALF_UP);
            }
            associationVO.setAveragePrice(averagePrice);
        }
        return list;
    }
}